/*
 * Copyright 2013 NJUT  qixiaobo. All rights reserved.
 */
package com.fujitsu.nanjing.tieba.trigger;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Scope;

import com.fujitsu.nanjing.tieba.ibator.CoreVisitStat;
import com.fujitsu.nanjing.tieba.service.ReplyService;
import com.fujitsu.nanjing.tieba.service.TopicService;
import com.fujitsu.nanjing.tieba.service.UserService;
import com.fujitsu.nanjing.tieba.service.VisitStatService;

/**
 * FluxTrigger.java
 * 
 * @author Administrator
 */
@Configurable("fluxTrigger")
@Scope
@DependsOn
public class FluxTrigger implements Job {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(FluxTrigger.class);

	private VisitStatService visitStatService;
	private TopicService topicService;
	private UserService userService;
	private ReplyService replyService;
	private static DateFormat df;
	static {
		df = new SimpleDateFormat("yyyy-MM");
	}
	@Override
	public void execute(JobExecutionContext context)
			throws JobExecutionException {
		peform();
		logger.info("FluxTrigger执行！" + new Date().toString());
	}
	private void peform() {
		Date now = new Date();
		String _key = df.format(now);
		CoreVisitStat visit = visitStatService.findById(_key);
		CoreVisitStat t = getFlux(_key);
		if (visit == null) {
			visitStatService.insert(t);
		} else {
			visitStatService.update(t);
		}

	}
	private CoreVisitStat getFlux(String _key) {
		CoreVisitStat t = new CoreVisitStat();
		t.setStatdate(_key);
		t.setTopics(topicService.countMonthNewTopics());
		t.setReplies(replyService.countMonthNewReplies());
		t.setUsers(userService.countMonthNewUsers());
		t.setVisits(topicService.sumOfVisits());
		return t;
	}
	public VisitStatService getVisitStatService() {
		return visitStatService;
	}
	public void setVisitStatService(VisitStatService visitStatService) {
		this.visitStatService = visitStatService;
	}
	public TopicService getTopicService() {
		return topicService;
	}
	public void setTopicService(TopicService topicService) {
		this.topicService = topicService;
	}
	public UserService getUserService() {
		return userService;
	}
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	public ReplyService getReplyService() {
		return replyService;
	}
	public void setReplyService(ReplyService replyService) {
		this.replyService = replyService;
	}

	protected static String format(Date date) {

		return df.format(date);
	}

}
